package com.sise.aio和bio和nio.aio.基于aio的聊天室;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.AsynchronousChannel;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @author idea
 * @data 2019/1/22
 */
public class Server2 {

    public static void main(String[] args) throws IOException {
        final AsynchronousServerSocketChannel channel=AsynchronousServerSocketChannel .open().bind(new InetSocketAddress(InetAddress.getLocalHost(),8088));
        channel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

            @Override
            public void completed(final AsynchronousSocketChannel client, Object attachment) {
                channel.accept(null,this);
                ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                client.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        attachment.flip();
                        CharBuffer charBuffer = CharBuffer.allocate(1024);
                        CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
                        decoder.decode(attachment,charBuffer,false);
                        charBuffer.flip();
                        String data = new String(charBuffer.array(),0, charBuffer.limit());
                        System.out.println("read data:" + data);
                        try{
                            client.close();
                        }catch (Exception e){}
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        System.out.println("出现异常！");
                    }
                });
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.out.println("accept error");
            }
        });
        System.out.println("server end!");
    }

}
